﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AsycServer
{
    /// <summary>
    /// 服务端逻辑启动
    /// </summary>
    public partial class AsyUdpServer
    {
        public string LocalIP
        {
            get
            {
                IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
                string localIP = "";

                foreach (IPAddress ip in host.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        localIP = ip.ToString();
                        break;
                    }
                }

                return localIP;
            }
        }
        
        /// <summary>
        /// UDP
        /// </summary>
        UdpClient udpSocket;
        private int udpPort;
        
        /// <summary>
        /// TCP
        /// </summary>
        TcpListener tcpSocket;
        private int tcpPort;
        
        public AsyUdpServer(int tcp, int udp)
        {
            tcpPort = tcp;
            udpPort = udp;
        }
        
        
        public void StartUp() { StartUp(LocalIP); }
        public void StartUp(string ip)
        {
            try
            {
                //开启UDP
                udpSocket = new UdpClient(udpPort);
                
                //开启TCP
                tcpSocket = new TcpListener(IPAddress.Any, tcpPort);

                acceptThread = new Thread(AcceptThread);
                receiveThread = new Thread(ReceiveThread);
                sendThread = new Thread(SendThread);

                acceptThread.Start();
                receiveThread.Start();
                sendThread.Start();

                //启动完Socket后执行回调
                OnStart();
            }
            catch (Exception e)
            {
                CatchException(e);
            }
        }
    }
}